import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { showLoading, hideLoading } from "./loading";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, //
  timeout: 50000 // request timeout
});

// request interceptor
// 请求拦截
service.interceptors.request.use(
  config => {
    // console.log('config: ', config);
    if (!(config.url.indexOf('v1/file-upload/LogfileUpload') > -1 || config.url.indexOf('v1/app/AppStatus') > -1 ||
      config.url.indexOf('v1/appEntity/getApp') > -1 || config.url.indexOf('v1/device-restart/page') > -1 ||
      config.url.indexOf('v1/device-state-result/page') > -1 || config.url.indexOf('v1/networkInfo/getByMessageId') > -1 ||
      config.url.indexOf('v1/app-task/byTaskId') > -1 || config.url.indexOf('v1/container') > -1)
    ) {
      showLoading();
    }
    // do something before request is sent
    // let cip = returnCitySN["cip"];
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["Authorization"] = getToken();
      // config.headers["x-forwarded-for"] = cip;
    }
    return config;
  },
  error => {
    // do something with request error
    hideLoading();
    return Promise.reject(error);
  }
);

// response interceptor
//响应拦截
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data ? response.data : response;
    hideLoading();
    var curMsg = "";
    if (res.code && res.code !== 200) {
      switch (res.code) {
        case 400:
          // curMsg = "错误请求";
          break;
        case 400:
          // curMsg = "错误请求";
          break;
        case 401:
          curMsg = "未授权，请重新登录";
          // setTimeout(() => {
          //   store.dispatch("user/resetToken").then(() => {
          //     location.reload();
          //   });
          // }, 1000);

          break;
        case 403:
          // curMsg = '拒绝访问'
          curMsg = "未授权，请重新登录";
          // setTimeout(() => {
          //   store.dispatch("user/resetToken").then(() => {
          //     location.reload();
          //   });
          // }, 1000);

          break;
        case 404:
          curMsg = "请求错误，未找到该资源";
          break;
        case 405:
          curMsg = "请求方法未允许";
          break;
        case 408:
          curMsg = "请求超时";
          break;
        case 500:
          // curMsg = "后台服务出错";
          break;
      }
      Message({
        message: res.message,
        type: "error",
        duration: 5 * 1000
      });
      // return res;
    } else {
      return res;
    }
  },
  error => {
    // 超时处理
    if (error && error.stack.indexOf("timeout") > -1) {
      Message({
        message: "请求超时了",
        type: "error",
        duration: 5 * 1000
      });
      hideLoading();
      return Promise.reject(error);
    }
    // 非超时错误处理
    var curMsg = "";
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          curMsg = "错误请求";
          break;
        case 400:
          curMsg = "错误请求";
          break;
        case 401:
          curMsg = "未授权，请重新登录";
          setTimeout(() => {
            store.dispatch("user/resetToken").then(() => {
              location.reload();
            });
          }, 1000);

          break;
        case 403:
          // curMsg = '拒绝访问'
          curMsg = "未授权，不能操作";
          // setTimeout(() => {
          //   store.dispatch("user/resetToken").then(() => {
          //     location.reload();
          //   });
          // }, 1000);

          break;
        case 404:
          curMsg = "请求错误，未找到该资源";
          break;
        case 405:
          curMsg = "请求方法未允许";
          break;
        case 408:
          curMsg = "请求超时";
          break;
        case 500:
          curMsg = error.response.data;
          break;
      }
    }
    hideLoading();
    // if (error.response.status != 500) {
      Message({
        message: curMsg,
        type: "error",
        duration: 5 * 1000
      });
    // }

    return Promise.reject(error);
  }
);

export default service;
